package com.ly.mp.busicen.rule;

import java.util.concurrent.atomic.AtomicBoolean;

import javax.annotation.PostConstruct;

import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Configuration;

import com.ly.mp.busicen.common.helper.SpringContextHolder;


// 重新 validate 和 rule的方法
@Configuration
public class RuleReloadService implements ApplicationRunner{

	private static final Logger log = LoggerFactory.getLogger(RuleReloadService.class);
	
	AtomicBoolean postOk=new AtomicBoolean(true);
	
	@Autowired
	IRuleReload ruleReload;
	
	@ConditionalOnBean({ApplicationConfig.class,RegistryConfig.class,ProtocolConfig.class})
	@PostConstruct
	public void registReload() {
		if (postOk.get()) {
			exportService(IRuleReload.class, ruleReload);
		}
		
	}

	public <T> void exportService(Class<T> clazz, T t) {
		postOk.set(false);
		try {
			ApplicationConfig application = (ApplicationConfig) SpringContextHolder.getBean(ApplicationConfig.class);
			if (application == null) {
				throw new RuntimeException("ApplicationConfig 未配置");
			}
			RegistryConfig registry = (RegistryConfig) SpringContextHolder.getBean(RegistryConfig.class);
			if (registry == null)
				throw new RuntimeException("RegistryConfig 未配置");

			ProtocolConfig protocol = (ProtocolConfig) SpringContextHolder.getBean(ProtocolConfig.class);

			try {
				ServiceConfig<T> service = new ServiceConfig<>();
				service.setApplication(application);
				service.setRegistry(registry);
				service.setProtocol(protocol);
				service.setInterface(clazz);
				service.setTimeout(120000);
				service.setRef(t);
				service.export();
				log.info("export {} service success[{}]", clazz.getName(), service.getExportedUrls().get(0).getPort());
				
			} catch (Exception e) {
				log.error("export " + clazz.getName() + " service fail", e);
				throw new RuntimeException("export fail");
			}
		} catch (Exception e) {
			postOk.set(true);
			log.error("未配置dubbo");
		}
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {
		registReload();
	}

}
